package wxpay

import (
	"encoding/json"
	"fmt"
)

type WxPayMch struct {
	MchParam
}

//支付订单查询
//transaction_id:微信支付订单号
//mchid:商户号
func (ent *WxPayMch)QueryByTransactionId(transaction_id string, mchid string) (WxPayInfo, error) {
	var par_info WxPayInfo
	url := fmt.Sprintf("https://api.mch.weixin.qq.com/v3/pay/transactions/id/%s?mchid=%s", transaction_id, mchid)
	result, err := WxPayGetV3(&ent.MchParam, url)
	if err != nil {
		fmt.Println(err)
		return par_info, err
	}
	err = json.Unmarshal([]byte(result), &par_info)
	if err != nil {
		fmt.Println(err)
		return par_info, err
	}

	return par_info, nil
}

//支付订单查询
//out_trade_no:业务订单号
//mchid:商户号
func (ent *WxPayMch)QueryByOutTradeNo(out_trade_no string, mchid string) (WxPayInfo, error) {
	var par_info WxPayInfo
	url := fmt.Sprintf("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s?mchid=%s", out_trade_no, mchid)
	result, err := WxPayGetV3(&ent.MchParam, url)
	if err != nil {
		return par_info, err
	}
	err = json.Unmarshal([]byte(result), &par_info)
	if err != nil {
		return par_info, err
	}

	return par_info, nil
}

//关闭支付订单
//out_trade_no:业务订单号
//mchid:商户号
func (ent *WxPayMch)CloseOrder(out_trade_no string, mchid string) error {
	type CloseOrderReq struct {
		Mchid          		string	`json:"mchid,omitempty"`
	}
	var preq CloseOrderReq
	preq.Mchid = mchid
	data_body, _ := json.Marshal(preq)

	url := fmt.Sprintf("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s/close", out_trade_no)
	_, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return  err
	}
	return  nil
}

//提交退款申请
func (ent *WxPayMch)RefundOrder(data RefundCreateReq) (RefundOrderInfo, error) {
	data.Sub_mchid = ""
	if data.Amount.Currency == "" {
		data.Amount.Currency = "CNY"
	}
	data_body, _ := json.Marshal(data)

	var pret RefundOrderInfo
	const url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"
	result, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return pret, err
	}
	err = json.Unmarshal([]byte(result), &pret)
	if err != nil {
		return pret, err
	}
	return pret, nil
}

//查询单笔退款
//out_refund_no:商户系统内部的退款单号
//mchid:商户号
func (ent *WxPayMch)QueryRefundOrder(out_refund_no string, mchid string) (RefundOrderInfo, error) {
	var ret_info RefundOrderInfo
	url := fmt.Sprintf("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds/%s", out_refund_no)
	result, err := WxPayGetV3(&ent.MchParam, url)
	if err != nil {
		fmt.Println(err)
		return ret_info, err
	}
	err = json.Unmarshal([]byte(result), &ret_info)
	if err != nil {
		fmt.Println(err)
		return ret_info, err
	}

	return ret_info, nil
}
